package com.hsl.hslcodemother.ai.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hsl.hslcodemother.ai.model.HtmlCodeResult;
import com.hsl.hslcodemother.ai.model.MultiFileCodeResult;
import com.hsl.hslcodemother.ai.model.enums.CodeGenTypeEnum;
import com.hsl.hslcodemother.constant.AppConstant;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @Date 2025/9/5 17:21
 * @Author hsl
 */
public class CodeFileSaver {
    private static final String FILE_SAVE_ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;

    public static File saveHtmlCodeResult(HtmlCodeResult result, Long appId) {
        String baseDir = buildUniqueDir(CodeGenTypeEnum.HTML.getValue(), appId);
        writeToFile(baseDir, "index.html", result.getHtmlCode());
        return new File(baseDir);
    }

    public static File saveMultiFileCodeResult(MultiFileCodeResult result, Long appId) {
        String baseDir = buildUniqueDir(CodeGenTypeEnum.MULTI_FILE.getValue(), appId);
        writeToFile(baseDir, "index.html", result.getHtmlCode());
        writeToFile(baseDir, "style.css", result.getCssCode());
        writeToFile(baseDir, "script.js", result.getJsCode());
        return new File(baseDir);
    }


    /**
     * 构建唯一目录路径：tmp/code_output/bizType_雪花ID
     */
    private static String buildUniqueDir(String bizType, Long appId) {
        String uniqueDirName = StrUtil.format("{}_{}", bizType, appId);
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniqueDirName;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    /**
     * 写入单个文件
     */
    private static void writeToFile(String dirPath, String filename, String content) {
        String filePath = dirPath + File.separator + filename;
        FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);
    }
}
